#!/usr/bin/python3
#
# Copyright (C) 2021  FreeIPA Contributors see COPYING for license
#

import logging

from ipalib import api
from ipalib.install import sysrestore
from ipaplatform.paths import paths
from ipapython import ipaldap
from ipapython.admintool import AdminTool
from ipaserver.install import adtrust, adtrustinstance

logger = logging.getLogger(__name__)

class IPAConfigEnableSid(AdminTool):
    command_name = "ipa-enable-sid"
    log_file_name = paths.IPASERVER_ENABLESID_LOG
    usage = "%prog"
    description = "Enable SID generation"

    @classmethod
    def add_options(cls, parser):
        super(IPAConfigEnableSid, cls).add_options(parser)

        parser.add_option(
            "--add-sids",
            dest="add_sids", default=False, action="store_true",
            help="Add SIDs for existing users and groups as the final step"
        )

        parser.add_option(
            "--netbios-name",
            dest="netbios_name", default=None,
            help="NetBIOS name of the IPA domain"
        )

        parser.add_option(
            "--reset-netbios-name",
            dest="reset_netbios_name", default=False, action="store_true",
            help="Force reset of the existing NetBIOS name"
        )


    def validate_options(self):
        super(IPAConfigEnableSid, self).validate_options(needs_root=True)

    def run(self):
        api.bootstrap(in_server=True, confdir=paths.ETC_IPA)
        api.finalize()

        try:
            api.Backend.ldap2.connect()
            fstore = sysrestore.FileStore(paths.SYSRESTORE)

            smb = adtrustinstance.ADTRUSTInstance(fstore, False)
            smb.realm = api.env.realm
            smb.autobind = ipaldap.AUTOBIND_ENABLED
            smb.setup(api.env.host, api.env.realm,
                      self.options.netbios_name,
                      self.options.reset_netbios_name,
                      adtrust.DEFAULT_PRIMARY_RID_BASE,
                      adtrust.DEFAULT_SECONDARY_RID_BASE,
                      self.options.add_sids,
                      enable_compat=False)
            smb.find_local_id_range()
            smb.create_instance()

        finally:
            if api.Backend.ldap2.isconnected():
                api.Backend.ldap2.disconnect()

        return 0

IPAConfigEnableSid.run_cli()
